<?php
/* 
 *交易action 公共类：enter,sale。。。switch均可继承
 */
class TransAction extends CommonAction {
   
    public function _before_add(){
        $this->assign('users',getModelIdName('User'));
        $this->assign('warehouses',getModelIdName('Warehouse'));
    }

    public function _before_edit(){
        $this->assign('users',getModelIdName('User'));
        $this->assign('warehouses',getModelIdName('Warehouse'));
    }

   

    public function insert(){
       //TODO 重复退货的控制
         $model = $this->getActionName();
         $Model = D($model);
         $pid = $_POST['product_id'];
         if(!$pid)
            $this->error('请选择至少一个产品');
        if($pid != array_unique($pid)){
          //采购或进货 如果有赠送赠品的，则可允许输入多行相同产品，赠品价格必须为0
          if(strtolower($model) == 'enter' || strtolower($model) == 'buy' ){
            $repeat_key  = array_diff_assoc($pid, array_unique($pid) );
           
            $repeat_first_index = 0 ; //get repeat array index
            foreach ($repeat_key as $k1 => $v1) {
              $repeat_first_index = $k1;  //仅取第一个索引
              break;
            }
            $enter_price_array = $_POST['enter_price'];
            if($enter_price_array[$repeat_first_index] != 0 )  //如果进价为0，则不提示
              $this->error('您选择的产品存在重复，请去重后再操作！');

          }else
              $this->error('您选择的产品存在重复，请去重后再操作！');
        }

          $number = $_POST['number'];
          foreach ($number as $key => $value) {
            if($value <1 )
              $this->error("产品数量必须大于等于 1 ");
            continue;
          }

          if($model == 'Sale' || $model == 'Wholesale'){
              if( $model == 'Sale' && empty($_POST['order_source_id']) )
                  $this->error('请选择订单来源！');

                if( $model == 'Wholesale' && empty($_POST['wholesale_source_id']) )
                  $this->error('请选择订单来源！');

              if(empty ($_POST['customer_id']) ){
                  $customer_id = getCustomerId($_POST['customer_name'],$_POST ['alipay'] );
                  $_POST ['customer_id'] = $customer_id ;
              }
                $_POST['customer_name'] = getModelName( $_POST ['customer_id'],'Customer' );
                $_POST['shipping_name'] = empty($_POST['shipping_name'])? $_POST['customer_name']: $_POST['shipping_name'] ;
                 $shipping_address_id = getShippingAddressId($customer_id ,$_POST['shipping_name'],$_POST ['address'],$_POST ['mobile'],$sdata ['phone'] );
                 $_POST ['shipping_address_id'] = $shipping_address_id ;
            }

        if( $model == 'Buy' && ($_POST['supplier_id'] < 1) ){
           $this->error('请选择供应商!');
        }
        if(false == $Model->create()) {
            $this->error($Model->getError());
        }
        if(false !== $list = $Model->add()) {
          //如果是销售，则增加对应的客户及收货地址
            

            $this->__process_enter_detail($list);
            $mod_field = getModelName ($list, $model);
            $msg = '新增 '.$model.': '.$mod_field.' (编号：'.$list.')';
            A('Action')->writeLog($msg,'新增',$model,$list);
            $this->assign ( 'jumpUrl', '__URL__' ); //return index list
            $this->success('添加成功');
        }
        else {
            $this->error('新增失败！');
        }
    }

   

    protected function __process_enter_detail($trans_id){
        $model = $this->getActionName();
        $m = strtolower($model);
        $data =array(
                'product_id'=>$_POST['product_id'],
                'order_source_id'=>$_POST['order_source_id'],
                'lot'=>$_POST['lot'], //产品批号
                'exp'=>$_POST['exp'], //截止有效期
                'number'=>$_POST['number'],
                $m.'_id'=>$trans_id,
                $m.'_no' => getModelName($trans_id, $model,$m.'_no'),
        );

        $val_data = array();
        switch ($m) {
            case 'sale':
                $val_data =array(
                        'price'=>$_POST['price'],
                        'customer_id'=> $_POST['customer_id'],
                        'sale_title' => $_POST['sale_title'],
                );
                break;
            case 'wholesale':
                $val_data =array(
                        'price'=>$_POST['price'],
                        'customer_id'=> $_POST['customer_id'],
                );
                break;
            case 'sale_back':
                $val_data =array(
                        'price'=>$_POST['price'],
                        'sale_id'=>$_POST['sale_id'],
                        'reason'=>$_POST['reason'],
                        'customer_id'=>$_POST['customer_id'],
                );
                break;
            case 'back_supplier':
                $val_data =array(
                        'price'=>$_POST['price'],
                        'supplier_id'=>$_POST['supplier_id'],
                        'reason'=>$_POST['reason'],
                );
                break;
            case 'broken':
                $val_data =array(
                  'price'=>$_POST['price'],
                  'reason'=>$_POST['reason'],
                );
                break;
            case 'switch':
                $val_data =array(
                        'from_warehouse_id'=>$_POST['from_warehouse_id'],
                        'to_warehouse_id'=>$_POST['to_warehouse_id'],
                );
                break;
            case 'buy':
                $val_data =array(
                        'enter_price'=>$_POST['enter_price'],
                        'supplier_id'=>$_POST['supplier_id'],
                );
                break;

            case 'enter':
            default:
                 $val_data =array(
                        'buy_id' => $_POST['buy_id'],
                        'finish' => $_POST['finish'],
                        'buy_detail_id'=>$_POST['buy_detail_id'],
                        'enter_price'=>$_POST['enter_price'],
                        'supplier_id'=>$_POST['supplier_id'],
                );
                break;
        }
        $data = array_merge($data,$val_data);

        $status =  $this->addDetail($data);
        if (!$status) {
            $this->errmsg .= "<br/>";
            $this->errmsg .=  '详情插入出现问题！';
        }
        return;
    }

    protected function addDetail($data){
       $small_count = count($data['product_id']);
           $detail_data = array();
           $new_id = 0; //插入的新数据ID
           //$model = M('Sale_detail');
           $big_m = $this->getActionName();
           $model = M($big_m.'_detail');
           $m = strtolower( $big_m );//变小写
           $total = 0; //total money @overview table
           $sum_number = 0; //sum total number
           $cache_goods = S('goods');

           switch ($m) {
               case 'sale': {
                       for( $i =0 ; $i<$small_count;$i++) {
                           $detail_data= array(
                                   $m.'_id'=> $data[$m.'_id'],
                                   $m.'_no'=> $data[$m.'_no'],
                                   'product_id'=> $data['product_id'][$i],
                                   'lot'=> $data['lot'][$i],   //产品批号
                                   'exp'=> $data['exp'][$i],   //截止有效期
                                   'price'=> $data['price'][$i],
                                   'number'=> $data['number'][$i],
                                   'total' => $data['price'][$i]*$data['number'][$i],
                                   'customer_id'=> $data['customer_id'],    //冗余设计
                                   'create_time'=> time(),
                                   'out_number' => getOut_number($data['product_id'][$i],$data['order_source_id'] ), //第三方编码
                                    'sale_title' => empty($data['sale_title'][$i]) ? makeSale_title( $data['product_id'][$i]) : $data['sale_title'][$i], 
                                    'warehouse_id' => $cache_goods[$data['product_id'][$i]]['warehouse_id'],
                   
                           );
                           $new_id = $model ->add($detail_data);
                           if($new_id > 0){
                               $total += $detail_data['total'];
                               $sum_number += $detail_data['number'];
                           }
                           unset($detail_data);
                           $new_id = 0;
                       }
                       //更新大表总金额，总数量
                       $total_data = array('total'=>$total,'sum_number'=>$sum_number);
                       M($big_m)->where('id = '.$data[$m.'_id'])->save($total_data);
                       $total = 0 ;
                       $sum_number = 0;
                       return true;
                   }
                   break;
              case 'wholesale': {
                       for( $i =0 ; $i<$small_count;$i++) {
                           $detail_data= array(
                                   $m.'_id'=> $data[$m.'_id'],
                                   $m.'_no'=> $data[$m.'_no'],
                                   'product_id'=> $data['product_id'][$i],
                                   'lot'=> $data['lot'][$i],   //产品批号
                                   'exp'=> $data['exp'][$i],   //截止有效期
                                   'price'=> $data['price'][$i],
                                   'number'=> $data['number'][$i],
                                   'total' => $data['price'][$i]*$data['number'][$i],
                                   'customer_id'=> $data['customer_id'],    //冗余设计
                                   'create_time'=> time(),
                                   
                           );
                           $new_id = $model ->add($detail_data);
                           if($new_id > 0 ){
                               $total += $detail_data['total'];
                               $sum_number += $detail_data['number'];
                            }
                           unset($detail_data);
                           $new_id = 0;
                       }
                       //更新大表总金额，总数量
                       $total_data = array('total'=>$total,'sum_number'=>$sum_number);
                       M($big_m)->where('id = '.$data[$m.'_id'])->save($total_data);
                       $total = 0 ;
                       $sum_number = 0;
                       return true;
                   }
                   break;
              case 'sale_back': {
                       for( $i =0 ; $i<$small_count;$i++) {
                           $detail_data= array(
                                   $m.'_id'=> $data[$m.'_id'],
                                   $m.'_no'=> $data[$m.'_no'],
                                   'product_id'=> $data['product_id'][$i],
                                   'lot'=> $data['lot'][$i],   //产品批号
                                   'exp'=> $data['exp'][$i],   //截止有效期
                                   'price'=> $data['price'][$i],
                                   'number'=> $data['number'][$i],
                                   'total' => $data['price'][$i]*$data['number'][$i],
                                   'customer_id'=> $data['customer_id'],    //冗余设计
                                   'reason'=> $data['reason'][$i],
                                    'sale_id'=> $data['sale_id'][$i],
                                   'create_time'=> time(),
                           );
                           $new_id = $model ->add($detail_data);
                           if($new_id > 0){  //增加库存
                               $this->updateStock($data['product_id'][$i], getModelName($data[$m.'_id'], $big_m, 'warehouse_id'), 'in', $data['number'][$i]);
                               $total += $detail_data['total'];
                               $sum_number += $detail_data['number'];
                           }
                           unset($detail_data);
                           $new_id = 0;
                       }
                       //更新大表总金额
                       $total_data = array('total'=>$total,'sum_number'=>$sum_number);
                       M($big_m)->where('id = '.$data[$m.'_id'])->save($total_data);
                       $total = 0 ;
                       $sum_number = 0;
                       return true;
                   }
                   break;
               case 'back_supplier': {
                       for( $i =0 ; $i<$small_count;$i++) {
                           $detail_data= array(
                                   $m.'_id'=> $data[$m.'_id'],
                                   $m.'_no'=> $data[$m.'_no'],
                                   'product_id'=> $data['product_id'][$i],
                                   'lot'=> $data['lot'][$i],   //产品批号
                                   'exp'=> $data['exp'][$i],   //截止有效期
                                    'price'=> $data['price'][$i],
                                   'number'=> $data['number'][$i],
                                   'total' => $data['price'][$i]*$data['number'][$i],
                                   'supplier_id'=> $data['supplier_id'],//冗余设计
                                   'reason'=> $data['reason'][$i],
                                   'create_time'=> time(),
                           );
                           $new_id = $model ->add($detail_data);
                           if($new_id > 0){  //减去库存
                               $this->updateStock($data['product_id'][$i], getModelName($data[$m.'_id'], $big_m, 'warehouse_id'), 'out', $data['number'][$i]);
                               $total += $detail_data['total'];
                               $sum_number += $detail_data['number'];
                           }
                           unset($detail_data);
                           $new_id = 0;
                       }
                       //更新大表总金额
                       $total_data = array('total'=>$total,'sum_number'=>$sum_number);
                       M($big_m)->where('id = '.$data[$m.'_id'])->save($total_data);
                       $total = 0 ;
                       $sum_number = 0;
                       return true;
                   }
                   break;
               case 'broken': {
                       for( $i =0 ; $i<$small_count;$i++) {
                           $detail_data= array(
                                   $m.'_id'=> $data[$m.'_id'],
                                   $m.'_no'=> $data[$m.'_no'],
                                   'product_id'=> $data['product_id'][$i],
                                   'lot'=> $data['lot'][$i],   //产品批号
                                   'exp'=> $data['exp'][$i],   //截止有效期
                                   'number'=> $data['number'][$i],
                                   'price'=> $data['price'][$i],
                                   'total' => $data['price'][$i]*$data['number'][$i],
                                   'reason'=> $data['reason'][$i],
                                   'create_time'=> time(),
                           );
                           $new_id = $model ->add($detail_data);
                           if($new_id > 0){
                               
                           $total += $detail_data['total'];
                            $sum_number += $detail_data['number'];
                           //减去库存
                           //报废库存TODO
                            $this->updateStock($data['product_id'][$i], getModelName($data[$m.'_id'], $big_m, 'warehouse_id'), 'out', $data['number'][$i]);
                            }
                           unset($detail_data);
                       }
                       $total_data = array('total'=>$total,'sum_number'=>$sum_number);
                       M($big_m)->where('id = '.$data[$m.'_id'])->save($total_data);
                       //$total = 0 ;
                       $sum_number = 0;
                       return true;
                   }
                   break;
                case 'switch': {
                       for( $i =0 ; $i<$small_count;$i++) {
                           $detail_data= array(
                                   $m.'_id'=> $data[$m.'_id'],
                                   $m.'_no'=> $data[$m.'_no'],
                                   'product_id'=> $data['product_id'][$i],
                                   'lot'=> $data['lot'][$i],   //产品批号
                                   'exp'=> $data['exp'][$i],   //截止有效期
                                   'number'=> $data['number'][$i],
                                   'from_warehouse_id'=> $data['from_warehouse_id'][$i],
                                   'to_warehouse_id'=> $data['to_warehouse_id'][$i],
                                   'create_time'=> time(),
                           );
                           if($data['from_warehouse_id'][$i] != $data['to_warehouse_id'][$i] )
                                $new_id = $model ->add($detail_data); //如果目标仓库和来源 仓库相同，则不做操作
                           if($new_id > 0){
                               $this->updateStock($data['product_id'][$i], $data['from_warehouse_id'][$i], 'out', $data['number'][$i]);
                               $this->updateStock($data['product_id'][$i], $data['to_warehouse_id'][$i], 'in', $data['number'][$i]);
                           }
                           unset($detail_data);
                           $new_id = 0;
                       }
                       return true;
                   }
                   break;
              case 'buy':
              {
                $total = 0 ;
                $sum_number = 0;

                       for( $i =0 ; $i<$small_count;$i++) {
                           $detail_data= array(
                                   $m.'_id'=> $data[$m.'_id'],
                                   $m.'_no'=> $data[$m.'_no'],
                                   'product_id'=> $data['product_id'][$i],
                                   'lot'=> $data['lot'][$i],   //产品批号
                                   'exp'=> $data['exp'][$i],   //截止有效期 
                                   'enter_price'=> $data['enter_price'][$i],
                                   'number'=> $data['number'][$i],
                                   'total' => $data['enter_price'][$i]*$data['number'][$i],
                                   'supplier_id'=> is_array($data['supplier_id'])?$data['supplier_id'][$i]:$data['supplier_id'],//取共同的supplier
                                   'create_time'=> time(),
                           );
                           $new_id = $model ->add($detail_data);
                           if( $new_id >0 ){
                               $total += $detail_data['total'];
                               $sum_number += $detail_data['number'];
                            }
                           unset($detail_data);
                           $new_id = 0;
                       }
                       //更新大表总金额
                       $total_data = array('total'=>$total,'sum_number'=>$sum_number);
                       M('Buy')->where('id = '.$data[$m.'_id'])->save($total_data);
                       $total = 0 ;
                       $sum_number = 0;
                       return true;
                   }
                   break;
               case 'enter':
               default:
                   {
                       for( $i =0 ; $i<$small_count;$i++) {
                           $detail_data= array(
                                   $m.'_id'=> $data[$m.'_id'],
                                   $m.'_no'=> $data[$m.'_no'],
                                   'product_id'=> $data['product_id'][$i],
                                   'lot'=> $data['lot'][$i],   //产品批号
                                   'exp'=> $data['exp'][$i],   //截止有效期
                                   'buy_id' => empty($data['buy_id']) ? 0: $data['buy_id'], 
                                   'buy_detail_id' => empty($data['buy_detail_id'][$i])? 0 : $data['buy_detail_id'][$i],
                                   'enter_price'=> empty($data['enter_price'][$i])? 0 : $data['enter_price'][$i],
                                   'number'=> $data['number'][$i],
                                   'total' => $data['enter_price'][$i]*$data['number'][$i],
                                   'supplier_id'=> is_array($data['supplier_id'])?$data['supplier_id'][$i]:$data['supplier_id'],//取共同的supplier
                                   'create_time'=> time(),
                           );
                           $new_id = $model ->add($detail_data);
                           if($new_id > 0){
                            //增加库存
                               $this->updateStock($data['product_id'][$i], getModelName($data[$m.'_id'], $big_m, 'warehouse_id'), 'in', $data['number'][$i]);
                                $total += $detail_data['total'];
                               $sum_number += $detail_data['number'];

                               //更新buy_detail
                               if(!empty($data['buy_detail_id'][$i])){
                                  $buyData = array('receive_number'=>$data['number'][$i],'finish'=>$data['finish'][$i],
                                    'receive_total'=> $detail_data['total'] );
                                  M('Buy_detail')->where('id = '.$data['buy_detail_id'][$i])->save($buyData);
                               }
                                
                               unset($detail_data);
                           }  

                           $new_id = 0;
                       }
                       //更新大表总金额
                       $total_data = array('total'=>$total,'sum_number'=>$sum_number);
                       M($big_m)->where('id = '.$data[$m.'_id'])->save($total_data);
                       $receive_total_data = array('receive_total'=>$total,'receive_sum_number'=>$sum_number,'finish'=>is_all_finish($data['buy_id']));
                       M('Buy')->where('id = '.$data['buy_id'])->save($receive_total_data); //更新buy表
                       $total = 0 ;
                       $sum_number = 0;
                       return true;
                   }
                   break;
           }
           
   }

   /**
    *更新库存操作，如果存在对应产品编号，则在记录上进行增减；如果无，则增加记录
    *
    * @param <type> $product_id 产品编号
    * @param <type> $warehouse_id 仓库编号
    * @param <type> $type 默认为in，入库，增加库存
    * @param <int> $number 数量
    */
   public function updateStock($product_id,$warehouse_id,$type='in',$number){
       $map = array(
           'product_id' => $product_id,
           'warehouse_id' => $warehouse_id,
       );
       $stock = M('Stock');
        $pstock = $stock->where($map)->find();
        
        //在原来基础上增加或改变
        if(is_array($pstock)){
            switch ($type){
                 case 'out':{
                     $old_number = $stock->where($map)->getField('number');
                     if($old_number < $number )
                         $stock->setDec('number',$map,$old_number);
                     else
                        $stock->setDec('number',$map,$number);
                    break;
                 }

                //入库
                case 'in':
                default:
                    $stock->setInc('number',$map,$number);
            }
        }else{//空记录
             switch ($type){
                 case 'out':{
                     $product = getModelName ($product_id, 'Product');
                     $warehouse = getModelName ($warehouse_id, 'Warehouse');
                     $msg = '试图从仓库'.$warehouse.'(编号'.$warehouse_id.') 中取出产品'.$product.' (编号：'.$product_id.')  数量为'.$number.',而该产品无库存记录 ！';
                     A('Action')->writeLog($msg,'异常','Stock',0);
                    break;
                 }
                //入库
                case 'in':
                default:
                {
                    $map['number'] = $number;
                    $stock->add($map);
                }
                    
            }
        }
   }

}
?>
